import AsyncStorage from "@react-native-async-storage/async-storage";
import queryApi from "../api/query";

export const register = (email, password) => {
  return async (dispatch) => {
    try {
      console.log("Working on .......");
      const response = await queryApi.post("/user/signup", { email, password });
      await AsyncStorage.setItem("token", response.data.token);
      console.log("Token stored");

      dispatch({
        type: "REGISTER",
        payload: { token: response.data.token, role: response.data.userRole },
      });
    } catch (error) {
      dispatch({
        type: "add_error",
        payload: "Something went wrong with signup",
      });
      console.log("Someting wrong");
      console.log(error);
    }
  };
};

export const signin = (email, password) => {
  return async (dispatch) => {
    try {
      console.log("Working on .......");

      const response = await queryApi.post("/user/signin", { email, password });

      await AsyncStorage.setItem("token", response.data.token);
      console.log("Token stored");
      dispatch({
        type: "SIGNIN",
        payload: { token: response.data.token, role: response.data.userRole },
      });
    } catch (error) {
      dispatch({
        type: "add_error",
        payload: "Something went wrong with signin",
      });
      console.log("Someting wrong");
    }
  };
};

export const signout = () => {
  return async (dispatch) => {
    await AsyncStorage.clear();
    dispatch({ type: "SIGNOUT" });
  };
};

export const changeState = (value) => {
  return (dispatch) => {
    dispatch({ type: "CHANGESTATE", payload: value });
  };
};
